﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AG.Editor.Core.Data;
using System.IO;
using AG.Editor.Core.Settings;
using System.Xml.Linq;

namespace AG.Editor.Core.Stores
{
    public class AGESettingsStore
    {

        private const string s_config_file = @".\configs\settings.xml";
        private const string s_config_relative_folder = @".\configs\";
        private string _settingsFile;
        private string _settingsFolder;
        public AGESettingsStore(string basePath)
        {
            _settingsFile = Path.Combine(basePath, s_config_file);
            _settingsFolder = Path.Combine(basePath, s_config_relative_folder);
        }

        /// <summary>
        /// 
        /// 从目录.\configs\config.xml中读取配置信息
        /// </summary>
        /// <param name="appCode"></param>
        /// <returns></returns>
        public AGESettings GetSettings(string appCode)
        {
            if (!File.Exists(_settingsFile))
            {
                return null;
            }

            AGESettings settings = null;
            XDocument xDoc = XDocument.Load(_settingsFile);

            // 获取当前的工作空间
            List<XElement> xSettingList = xDoc.Element("settings").XGetElements("setting").ToList();
            for (int index = 0; index < xSettingList.Count; index++)
            {
                XElement xSetting = xSettingList[index];
                string xAppCode = xSetting.XGetAttrString("app-code");
                if (xAppCode == appCode)
                {
                    settings = new AGESettings(appCode);
                    XElement xWS = xSetting.Element("p");
                    settings.LatestEProjectPath = xWS.Attribute("path").Value;

                    XElement xSettingItem1 = xWS.Element("convert-to-png-black-transparent");
                    if (xSettingItem1.Value == "1")
                    {
                        settings.ConvertToPNGBlackTransparent = true;
                    }
                    else
                    {
                        settings.ConvertToPNGBlackTransparent = false;
                    }
                }
            }

            return settings;
        }

        /// <summary>
        /// 保存配置信息
        /// </summary>
        /// <param name="config"></param>
        public void SaveSettings(AGESettings config)
        {
            // 创建or更新,true:create, false:update
            bool isCreateOrUpdate = false;

            // 目录不存在，创建目录
            if (!Directory.Exists(_settingsFolder))
            {
                Directory.CreateDirectory(_settingsFolder);
                isCreateOrUpdate = true;
            }

            // 检测文件是否存在
            if (!isCreateOrUpdate && !File.Exists(_settingsFile))
            {
                isCreateOrUpdate = true;
            }

            if (isCreateOrUpdate)
            {
                // create
                CreateConfigFile(_settingsFile, config);
            }
            else
            {
                // update
                UpdateConfigFile(_settingsFile, config);
            }
        }

        /// <summary>
        /// create config file
        /// </summary>
        /// <param name="path"></param>
        /// <param name="config"></param>
        private void CreateConfigFile(string path, AGESettings config)
        {
            XDocument xDoc = new XDocument();
            XElement xRoot = new XElement("settings");
            xDoc.Add(xRoot);

            #region save latest project path
            XElement xSetting = new XElement("setting");
            xRoot.Add(xSetting);
            xSetting.Add(new XAttribute("app-code", config.AppCode));

            XElement xWS = new XElement("p");
            xWS.Add(new XAttribute("path", config.LatestEProjectPath));
            xSetting.Add(xWS);

            SaveSetting(xWS, config);

            #region save workspace history
            //XElement xHWSList = new XElement("histories");
            //xWS.Add(xHWSList);
            //foreach (var hws in config.HistoryWorkspace)
            //{
            //    XElement xHWS = new XElement("workspace");
            //    xWS.Add(new XAttribute("name", hws.Name));
            //    xWS.Add(new XAttribute("path", hws.Path));
            //    xHWSList.Add(xHWS);
            //}
            #endregion

            #endregion
            xDoc.Save(path);
        }

        /// <summary>
        /// update config file
        /// </summary>
        /// <param name="path"></param>
        /// <param name="config"></param>
        private void UpdateConfigFile(string path, AGESettings config)
        {
            XDocument xDoc = XDocument.Load(path);
            XElement xRoot = xDoc.Element("settings");

            XElement xCurrentSetting = null;

            List<XElement> xSettingList = xDoc.Element("settings").XGetElements("setting").ToList();
            for (int index = 0; index < xSettingList.Count; index++)
            {
                XElement xSetting = xSettingList[index];
                string xAppCode = xSetting.XGetAttrString("app-code");
                if (xAppCode == config.AppCode)
                {
                    xCurrentSetting = xSetting;
                }
            }

            if (xCurrentSetting == null)
            {
                xCurrentSetting = new XElement("setting");
                xRoot.Add(xCurrentSetting);
                xCurrentSetting.Add(new XAttribute("app-code", config.AppCode));
            }
            else
            {
                xCurrentSetting.RemoveAll();
                xCurrentSetting.Add(new XAttribute("app-code", config.AppCode));
            }

            XElement xWS = new XElement("p");
            xWS.Add(new XAttribute("path", config.LatestEProjectPath));
            xCurrentSetting.Add(xWS);

            SaveSetting(xWS, config);

            xDoc.Save(path);
        }

        private void SaveSetting(XElement xWS, AGESettings config)
        {
            XElement xSettingItem = new XElement("convert-to-png-black-transparent");
            if (config.ConvertToPNGBlackTransparent)
            {
                xSettingItem.Value = "1";
            }
            else
            {
                xSettingItem.Value = "0";
            }
            xWS.Add(xSettingItem);
        }
    }
}
